public class Solution449 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public String serialize(TreeNode root) {
        if (root==null){
            return "";
        }
        return String.valueOf(root.val) +
                '(' +
                serialize(root.left) +
                ")(" +
                serialize(root.right) +
                ')';
    }

    public TreeNode deserialize(String data) {
        if (data.length()==0){
            return null;
        }
        int count=0,rec=-1;
        char[] chars=data.toCharArray();
        for (int i=0;i<chars.length;i++) {
            if (chars[i]=='('){
                count++;
            }
            if (chars[i]==')'){
                count--;
                if (count==0){
                    rec=i;
                    break;
                }
            }
        }
        int t=data.indexOf('(');
        TreeNode treeNode=new TreeNode(Integer.parseInt(data.substring(0,t)));
        treeNode.left=deserialize(data.substring(t+1,rec));
        treeNode.right=deserialize(data.substring(rec+2,data.length()-1));
        return treeNode;
    }

    public static void main(String[] args) {
        System.out.println(new Solution449().deserialize(new Solution449().serialize(new TreeNode(1,new TreeNode(2),new TreeNode(3,new TreeNode(4),new TreeNode(5))))).right.right.val);
    }
}
